package com.mlnx.netty.base.handler;

import com.mlnx.common.utils.MyLog;
import com.mlnx.data.entity.BpInfo;
import com.mlnx.device.entity.Device;
import com.mlnx.device.session.core.XmbpDeviceSession;
import com.mlnx.netty.base.message.BpMessage;
import io.netty.channel.ChannelHandlerContext;

/**
 * Created by amanda.shan on 2018/2/12.
 */
public class PushBpHandle extends BaseSimpleChannelInboundHandler<BpMessage> {

    private MyLog log = MyLog.getLog(this.getClass());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BpMessage msg) throws Exception {
        XmbpDeviceSession session = (XmbpDeviceSession) sessionManager.getSession(ctx.channel());
        String deviceId = msg.getDeviceId();
        Device device= deviceNettyService.getDevice(deviceId);
        if (msg.getElectric() != null) {
            deviceBroadcastService.castXmbpElectric(msg.getPatientId(), msg.getElectric());
        } else {
            BpInfo bpInfo = new BpInfo();
            bpInfo.setDeviceId(deviceId);
            bpInfo.setPatientId(device.getPatientId());
            bpInfo.setTime(msg.getPacketTime());
            bpInfo.setHeart(msg.getHeart());
            bpInfo.setSbp(msg.getSbp());
            bpInfo.setDbp(msg.getDbp());
            bpInfo.setPosition(msg.getPosition());
            bpInfo.setMethod(msg.getMethod());
            deviceBroadcastService.castBpInfo(bpInfo);
            if(session!=null){
                if(session.getBpInfo()==null){
                    session.setBpInfo(bpInfo);
                }else {
                    if(session.getBpInfo().getTime()<bpInfo.getTime()){
                        session.setBpInfo(bpInfo);
                    }
                }
            }
        }


    }
}
